'''Test Suite Formatter

Not very well tested, but seems to work. Use at your own risk.
'''

import sys

import robot.errors
from robot.running import TestLibrary, UserLibrary
from robot.parsing.model import TestData
from robot.parsing.settings import _Setting
import robot.parsing.model
import textwrap

class RobotFormatter(object):
    def __init__(self, suite):
        self._suite = suite
    @property
    def settings(self):
        return ""
    @property
    def variables(self):
        return ""
    @property
    def testcases(self):
        return ""
    @property
    def keywords(self):
        return ""

class HtmlFormatter(RobotFormatter):
    file_format = "html"

    def __str__(self):
        '''Return the suite in the tsv format'''
        output = "\n\n".join(("<html>", 
                              self.head,
                              "<body>"
                              "<h1>%s</h1>" % self._suite.name,
                              self.settings,
                              self.variables,
                              self.testcases,
                              self.keywords, 
                              "</body>",
                              "</html>",
                              ))
        return output

    @property
    def head(self):
        head= '''
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <meta name="generator" content="RIDE" /> 
                <meta name="rf-template" content="False" /> 
                <style type="text/css">
                    html {
                      font-family: Arial,Helvetica,sans-serif;
                      background-color: white;
                      color: black;
                    }
                    table {
                      border-collapse: collapse;
                      empty-cells: show;
                      margin: 1em 0em;
                      border: 1px solid black;
                    }
                    th, td {
                      border: 1px solid black;
                      padding: 0.1em 0.2em;
                      height: 1.5em;
                      width: 12em;
                    }
                    th {
                      background-color: rgb(192, 192, 192);
                      color: black;
                      height: 1.7em;
                      font-weight: bold;
                      text-align: center;
                      letter-spacing: 0.1em;
                    }
                    td.name {
                      background-color: rgb(240, 240, 240);
                      letter-spacing: 0.1em;
                    }
                    td.name, th.name {
                      width: 10em;
                    }
                </style>
                <title>Junk</title>
            </head>
        '''
        return textwrap.dedent(head.strip("\n"))

    @property
    def settings(self):
                                  
        output = ["<table id='settings' border='1'>"]
        output.append("<tr>")
        output.append("<th class='name'>Setting</th>")
        output.append("<th>Value</th>")
        output.append("</tr>")
        for setting in self._suite.setting_table:
            # should calculate widest row so we can set
            # a colspan for the value...
            if setting.is_set():
                s = setting.as_list()
                output.append("<tr><td class='name'>%s</td>" % s[0])
                for cell in s[1:]:
                    output.append("<td>%s</td>" % cell)
                output.append("</tr>")
        output.append("</table>")
        return "\n".join(output)
            
    @property
    def variables(self):
        output = ["<table id='variables' border='1'>"]
        output.append("<tr>")
        output.append("<th class='name'>Variable</th>")
        output.append("<th>Value</th>")
        output.append("</tr>")
        for variable in self._suite.variable_table:
            v = variable.as_list()
            output.append("<tr><td class='name'>%s</td>"  % v[0])
            for col in v[1:]:
                output.append("<td>%s</td>" % col)
            output.append("</tr>")
        output.append("</table>")
        return "\n".join(output)

    @property
    def testcases(self):
        return "<p><b>test cases not implemented yet</b></p>"
        t = ["*Test Case*"]
        for testcase in self._suite.testcase_table:
            t.append(testcase.name)
            for setting in [item for item in testcase if isinstance(item, _Setting)]:
                if setting.is_set():
                    t.append("\t".join([""] + setting.as_list()))

            for step in testcase.steps:
                t.append("\t".join([""] + step.as_list()))
                if step.is_for_loop():
                    for substep in step.steps:
                        t.append("\t".join(["",""] + substep.as_list()))
            t.append("\n")
        return "\n".join(t)

    
    @property
    def keywords(self):
        return "<p><b>keywords not implemented yet</b></p>"
        t = ["*Keyword*"]
        for keyword in self._suite.keyword_table:
            t.append(keyword.name)
            for setting in [item for item in keyword if isinstance(item, _Setting)]:
                if setting.is_set():
                    t.append("\t".join([""] + setting.as_list()))
            for step in keyword.steps:
                t.append("\t".join([""] + step.as_list()))
                if step.is_for_loop():
                    for substep in step.steps:
                        t.append("\t".join(["",""] + substep.as_list()))
        return "\n".join(t)


class TsvFormatter(RobotFormatter):
    '''Save a test suite in .tsv (tab separated values) format'''
    file_format = "tsv"

    @property
    def settings(self):
        t = ["*Setting*"]
        for setting in self._suite.setting_table:
            if setting.is_set():
                t.append("\t".join(setting.as_list()))
        return "\n".join(t)
            
    @property
    def variables(self):
        t = ["*Variable*"]
        for variable in self._suite.variable_table:
            t.append("\t".join(variable.as_list()))
        return "\n".join(t)

    @property
    def testcases(self):
        t = ["*Test Case*"]
        for testcase in self._suite.testcase_table:
            t.append(testcase.name)
            for setting in [item for item in testcase if isinstance(item, _Setting)]:
                if setting.is_set():
                    t.append("\t".join([""] + setting.as_list()))

            for step in testcase.steps:
                t.append("\t".join([""] + step.as_list()))
                if step.is_for_loop():
                    for substep in step.steps:
                        t.append("\t".join(["",""] + substep.as_list()))
            t.append("\n")
        return "\n".join(t)

    
    @property
    def keywords(self):
        t = ["*Keyword*"]
        for keyword in self._suite.keyword_table:
            t.append(keyword.name)
            for setting in [item for item in keyword if isinstance(item, _Setting)]:
                if setting.is_set():
                    t.append("\t".join([""] + setting.as_list()))
            for step in keyword.steps:
                t.append("\t".join([""] + step.as_list()))
                if step.is_for_loop():
                    for substep in step.steps:
                        t.append("\t".join(["",""] + substep.as_list()))
        return "\n".join(t)

    def __str__(self):
        '''Return the suite in the tsv format'''

        return "\n\n".join((self.settings,
                          self.variables,
                          self.testcases,
                          self.keywords))

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "usage: %s suite" % sys.argv[0]
        print "where 'suite' is a path to a robot test suite"
        sys.exit(1)

    suite = TestData(parent=None, source=sys.argv[1])

#    sw = TsvFormatter(suite)
    sw = HtmlFormatter(suite)
    
    print sw


